package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.utils.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AjaxAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        JsonResult jsonResult = new JsonResult(true, "登录成功");
        String jsonData = JSON.toJSON(jsonResult).toString();
        PrintWriter writer = response.getWriter();
        writer.write(jsonData);


        return false;
    }

    //登录失败
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");

        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccess(false);

        if (e instanceof UnknownAccountException) {
            jsonResult.setMsg( "用户名错误");
        } else if (e instanceof IncorrectCredentialsException) {

            jsonResult.setMsg( "密码错误");
        } else {

            jsonResult.setMsg( "未知错误");
        }
        String jsonData = JSON.toJSON(jsonResult).toString();
        PrintWriter writer=null;

        try {
            writer=response.getWriter();
            writer.write(jsonData);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}

